<template>
  <div
    style="
      background: #eee;
      display: flex;
      flex-direction: column;
      height: 100vh;
    "
  >
    <div class="video_title">
      <van-icon name="arrow-left" class="icon" @click="goBack" />
      <p>视频学习</p>
    </div>
    <div v-show="showVideo">
      <video-player
        :class="classFunction()"
        ref="videoPlayer"
        :playsinline="true"
        :options="playerOptions"
        @ended="onPlayerEnded($event)"
        @timeupdate="onPlayerTimeupdate($event)"
        @loadeddata="onPlayerLoadeddata($event)"
        @ready="playerReadied"
        @play="play"
        v-loading="loading"
        v-if="!aliDom"
      >
      </video-player>
      <div v-loading="loading" id="J_prismPlayer" v-else></div>
    </div>

    <div v-show="!showVideo" class="stBox" v-loading="loadingA">
      <div style="height: 100%" v-if="tableData.length == 0">
        <van-empty style="height: 70%" description="暂无数据"> </van-empty>
        <div
          style="
            display: flex;
            justify-content: center;
            width: 100%;
            margin-top: 30px;
          "
        >
          <el-button type="primary" @click="startExam">开始考试</el-button>
        </div>
      </div>
      <div v-else>
        <div style="display: flex; justify-content: center; width: 100%">
          <el-button type="primary" style="width: 100%" @click="startExam"
            >开始考试</el-button
          >
        </div>
        <div
          class="li"
          v-for="item in tableData"
          :key="item.id"
          @click="clickXq(item)"
        >
          <div class="li-top">
            <p>
              <span>状态:</span><i>{{ item.address }}</i>
            </p>
            <p>
              <span>成绩:</span><i>{{ item.score }}</i>
            </p>
          </div>
          <div class="li-bottom">
            <p>
              <span>考试用时:</span
              ><i>{{
                item.use_time >= 60
                  ? parseInt(item.use_time / 60) +
                    "分钟" +
                    (item.use_time % 60) +
                    "秒"
                  : item.use_time + "秒"
              }}</i>
            </p>
            <p>
              <span>提交时间:</span><i>{{ item.create_time }}</i>
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="videoName">
      <p>{{ titleName }}</p>
      <div>
        <el-button
          @click="startVideoPractice"
          class="videoPractice"
          v-if="
            (!qyType('test') || !qyType('tjy') || !qyType('qdshjg2')) &&
            status != 0
          "
          type="primary"
          icon="el-icon-edit"
        >
          视频练习</el-button
        >
      </div>
    </div>
    <div class="video_content" v-loading="loading">
      <li
        v-for="item in dataList"
        :key="item.id"
        @click="studyClick(item)"
        :class="item.id == id ? 'aivterLi' : ''"
      >
        <div class="font-box">
          <div
            :class="Boolean(item.done) ? 'content_text_boxA' : ''"
            style="width: 6.25rem; margin-right: 12px"
          >
            <img :src="item.cover_path" alt="" />
            <div class="card"></div>
            <div class="cardText">已看完</div>
          </div>
          <div style="flex: 1">
            <p>
              {{ item.title }}
            </p>
            <!-- <span>{{ item.create_time }}</span> -->
            <p style="width: 100%">
              <el-progress
                :percentage="
                  Boolean(item.status && item.status != 0)
                    ? 100
                    : Boolean(item.done)
                    ? 100
                    : Number((item.mprogress * 100).toFixed(0))
                "
              ></el-progress>
            </p>
          </div>
        </div>
        <!-- <div class="img_box">
                    <img :src="item.cover_path" alt="">
                </div> -->
      </li>
      <!-- v-if="Jurisdictions.随堂练习.模块展示 == '显示'" -->
      <li
        style="
          background: rgba(23, 93, 255, 0.08);
          padding-left: 0.75rem;
          padding-right: 0.75rem;
        "
      >
        <div class="font-box">
          <div>
            <p>随堂练习</p>
            <span
              >成绩：{{
                tableData.length != 0
                  ? tableData[tableData.length - 1].score
                  : "暂无记录"
              }}</span
            >
          </div>
        </div>
        <div class="img_box">
          <el-button
            @click="
              () => {
                if (this.aliDom)  {
                  this.Aliplayer.pause()
                } else {
                  this.$refs.videoPlayer.player.pause()
                }
                this.showVideo = false;
                this.id =  ''
              }
            "
            >查看练习记录</el-button
          >
        </div>
      </li>
      <div style="margin-bottom: 0.75rem" v-if="pdfOffIn.length != 0">
        <van-button type="info" block @click="goPDFList" color="#ffa833"
          >跳转至课件列表</van-button
        >
      </div>
      <div style="margin-bottom: 0.75rem">
        <van-button type="info" block @click="serachKnow"
          >学习下一知识点</van-button
        >
      </div>
    </div>
    <div
      style="
        position: absolute;
        top: 0;
        right: 0;
        height: 100vh;
        width: 100vw;
        z-index: 10;
        background: #d4d4d4;
      "
      v-if="disFace"
    >
      <face :comments="true" :show.sync="disFace" type="kjface"></face>
    </div>
    <van-popup
      v-model="dialogVisible"
      :close-on-click-overlay="false"
      :close-on-popstate="true"
      :style="{ height: '30%', width: '100vw', padding: '20px' }"
    >
      <p>
        -剩余验证时间:<span style="font-size: 22px; color: #f00">{{
          uTime
        }}</span
        >秒
      </p>
      <Verify
        type="2"
        :arith="1"
        width="100%"
        @success="verifySuccess"
        @error="verifyError"
        :figure="10"
      ></Verify>
    </van-popup>
  </div>
</template>

<script>
import Verify from "vue2-verify"; //验证码
import {
  materialList,
  materialaddlog,
  materiallearnlog,
  quizMylist,
  quizStart,
  getSetting,
  materialkmlist,
  aliVodInfo,
  videoPractice,
  gzExamSetting,
  quizRedo,
} from "@/api/admin.js";
import {
  getapplyid,
  getGZ,
  getsubject_id,
  getisfacetimekjface,
  getisfacetimezxface,
  getisfacetimemkface,
  getsubjectTitle,
  setExectSetting,
  getcurrentInfo,
} from "@/utils/auth";
import { learnImglist } from "@/utils/learnImg.js";
// import face from "@/components/Face/photo2.vue";
import face from "@/components/Face/photo.vue";
import { mapGetters } from "vuex";
//导出aliplayer

// 导出样式
import "aliyun-aliplayer/dist/skins/default/aliplayer-min.css";

import faceMode from "@/components/faceMode";
export default {
  components: { face, Verify },
  computed: { ...mapGetters(["Jurisdictions", "initObj"]) },
  data() {
    return {
      videoTestSetting: {},
      ...faceMode.data,
      allplayertime: 0,
      nowTime: 0,
      isdone: false,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", // 类型
            src: "", // url地址
          },
        ],
        poster: "@/assets/logo/1.gif", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      loading: false,
      timeNow: 0, // 当前时间
      timeNowA: 0, // 当前时间
      overTime: 0, //看完是 1  没看完是0
      titleName: "",
      id: this.$route.query.id,
      subjctid: this.$route.query.subjctid,
      src: "",
      dataList: [],
      isFalse: true,
      showVideo: true,
      tableData: [],
      loadingA: false,
      face: getisfacetimekjface() ? JSON.parse(getisfacetimekjface()).face : "", //人脸图像
      isquerymodel: true, //开启快进
      isjllog: false,
      http:
        process.env.NODE_ENV === "development"
          ? process.env.VUE_APP_BASE_API
          : window.location.href.slice(
              0,
              window.location.href.indexOf("/user")
            ),
      disFace: false,
      facetimeObj: Object, //人脸验证倒计时对象
      timeObj: Object, //A
      pdfOffIn: [],
      Aliplayer: "",
      aliDom:false,
      //阿里 播放器
      controlBarChildren: [
        { name: "progress", align: "blabs", x: 0, y: 44 }, //进度条
        { name: "playButton", align: "tl", x: 15, y: 12 }, //播放按钮
        { name: "timeDisplay", align: "tl", x: 10, y: 7 }, //播放时间
        { name: "fullScreenButton", align: "tr", x: 10, y: 12 }, //全屏按钮
        // {name:"subtitle", align:"tr",x:15, y:12},   //字幕
        { name: "speedButton", align: "tr", x: 15, y: 12 },
        { name: "qualityButton", align: "tr", x: 15, y: 12 },
        // {name:"setting", align:"tr",x:15, y:12,},  //设置
        { name: "volume", align: "tr", x: 5, y: 10 }, // 音量
      ],
      facetime: 0, //人脸验证时间

      windowPcltime: null,
      uTime: 0.2 * 60, //未确定 自动退出时间 单位  秒
      windowTime: 0 * 60, //未操作 自动退出时间  单位 秒
      outTime: null, //退出定时器

      dialogVisible: false, //验证码
      verifyNum: 0, //验证次数
      status: 0,
    };
  },
  watch: {
    // overTime(val){
    //     console.log(val)
    //     if(val){
    //         console.log(12111)
    //         this.addLog()
    //     }
    // }
    disFace(val) {
      this.$nextTick(() => {
        if (val) {
          clearTimeout(this.facetimeObj);
          if (this.windowTime && this.windowTime != 0) {
            this.OpenListening();
          }
        } else {
          this.$refs.videoPlayer.player.play();
          if (
            this.initObj.is_face &&this.Jurisdictions.gz&&
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
              "开启" &&
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime +
              ""
          ) {
            this.facetime = 0;
            if (
              JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                .kjfacetime == "随机"
            ) {
              this.facetime =
                Math.floor(
                  Math.random() *
                    (Number(
                      JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                        .kjfacetimeEnd
                    ) -
                      Number(
                        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                          .kjfacetimeStart
                      ) +
                      1)
                ) +
                Number(
                  JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                    .kjfacetimeStart
                );
            } else if (
              JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                .kjfacetime == "省厅规则"
            ) {
              this.facetime = 0;
              this.cyclesNum--;
              clearTimeout(this.facetimeObj);
              // if(this.cyclesNum<=0){
              // }
            } else {
              this.facetime = JSON.parse(this.initObj.is_face)[
                this.Jurisdictions.gz
              ].kjfacetime;
            }
            this.faceTimePause(this.facetime * 60 * 1000);
          }
          // this.$refs.time.start()
        }
      });
    },
    isquerymodel() {
      this.$forceUpdate();
    },
    timeNow(val, oval) {
      if (val && parseInt(val) != parseInt(oval)) {
        if (
          this.initObj.is_face &&this.Jurisdictions.gz&&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
            "开启" &&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime +
            ""
        ) {
          if (
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetime == "省厅规则"
          ) {
            this.showFaceMode(this.allplayertime, this);
            if (this.VerificationTime == parseInt(val)) {
              this.faceTimePause(1);
            }
            if (this.VerificationTime < parseInt(val)) {
              let num =
                this.allplayertime > 15 * 60
                  ? Math.floor(this.allplayertime / (15 * 60))
                  : 1;
              if (this.cyclesNum >= num) {
                this.faceTimePause(1);
              }
            }
          }
        }
      }
    },
    allplayertime(val) {
      if (val) {
        if (
          this.initObj.is_face &&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
            "开启" &&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime +
            ""
        ) {
          if (
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetime == "省厅规则"
          ) {
            let time = setTimeout(() => {
              faceMode.created(val, this); //获取验证次数
              clearTimeout(time);
            }, 1000);
          }
        }
      }
    },
  },
  methods: {
    ...faceMode.methods,
    notAlpay(time) {
      this.windowPcltime = setTimeout(() => {
        var setting = this.initObj?this.initObj.setting:''
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
          this.Aliplayer.pause();
        } else {
          this.$refs.videoPlayer.player.pause();
        }
        this.CloseListening();
        clearTimeout(this.facetimeObj);
        clearTimeout(this.windowPcltime);
        // var outTime =null
        // this.$toast({
        //   message:`您已${time}秒未操作界面~~~~~,请在一定时间内点击确认,否则将退出此界面 -剩余时间:${this.uTime}秒`,
        //   confirmButtonText: '确定',
        //   type:'warning',
        //   showClose:false,
        //   showCancelButton:false,
        //   closeOnClickModal:false,
        //   closeOnPressEscape:false,
        //   dangerouslyUseHTMLString:true,
        //   callback: action => {
        //     clearInterval(outTime)
        //     this.OpenListening()
        //   }
        // })
        var setting = this.initObj?this.initObj.setting:''
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
          if(this.Aliplayer.fullscreenService.getIsFullScreen()){
            this.Aliplayer.fullscreenService.cancelFullScreen() || this.Aliplayer.exitFullscreen()
          }
        } else {
          this.$refs.videoPlayer.player.exitFullscreen();
        }
        //
        if (
          JSON.parse(this.initObj.setting).vifivecode &&
          JSON.parse(this.initObj.setting).vifivecode == "验证码"
        ) {
          this.dialogVisible = true;
          this.outTime = setInterval(() => {
            // el-message-box__container
            this.uTime--;
            this.$forceUpdate();
            if (this.uTime == 0) {
              clearInterval(this.outTime);
              this.dialogVisible = false;
              this.goBack();
            }
          }, 1000);
        } else {
          this.$dialog.confirm(
            {
              title: "警告",
              message: `<div style='text-align: start;'>您已 ${time} 秒未操作界面,请在一定时间内点击确认,否则将退出此界面</div>- 剩余时间:<span style='font-size:22px;color:#f00;' id='outTime'>${this.uTime}</span>秒`,
              confirmButtonText: "确定",
              showClose: false,
              showCancelButton: false,
              allowHtml: true,
              beforeClose: (action, done) => {
                this.faceTimePause(this.facetime * 60 * 1000);
                clearInterval(this.outTime);
                this.OpenListening();
                done();
              },
          });
          // .van-dialog__message
          this.outTime = setInterval(() => {
            // el-message-box__container
            this.uTime--;
            if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器'){
              this.Aliplayer.pause();
            }else{
              this.$refs.videoPlayer.player.pause();
            }
            document.querySelector(
              "#outTime"
              ).innerText = this.uTime;
            // document.querySelector(".el-message-box__message").children[0].innerHTML = `您已${time}秒未操作界面~~~~~,请在一定时间内点击确认,否则将退出此界面 -剩余时间:${this.uTime}秒`
            this.$forceUpdate();
            if (this.uTime <= 0) {
              clearInterval(this.outTime);
              this.$dialog.close();
              this.goBack();
            }
          }, 1000);
          // setTimeout(()=>{
          // },3000)
        }
      }, time * 1000);
    },
    OpenListening() {
      this.uTime = 3 * 60; //自动退出时间设置
      document.addEventListener("touchstart", this.setTimeInfo);
      document.addEventListener("touchmove", this.setTimeInfo);
      // this.$refs.videoPlayer.player.touchstart=this.setTimeInfo
      // this.$refs.videoPlayer.player.touchmove=this.setTimeInfo
    },
    CloseListening() {
      document.removeEventListener("touchstart", this.setTimeInfo);
      document.removeEventListener("touchstart", this.setTimeInfo);
      // this.$refs.videoPlayer.player.touchstart = null
      // this.$refs.videoPlayer.player.touchmove = null
    },
    setTimeInfo() {
      clearTimeout(this.windowPcltime);
      this.notAlpay(this.windowTime);
    },
    //验证码 成功
    verifySuccess(obj) {
      this.verifyNum = 0;
      this.faceTimePause(this.facetime * 60 * 1000); //继续等待人脸验证
      this.dialogVisible = false;
      clearInterval(this.outTime);
      this.OpenListening();
      obj.refresh();
    },
    //验证码 失败
    verifyError() {
      this.$toast.fail("验证码错误!!!");
      this.verifyNum++;
      if (this.verifyNum == 3) {
        this.$toast.fail("验证次数已达3次,将退出本次学习~~~~");
        clearInterval(this.outTime);
        this.dialogVisible = false;
        this.goBack();
        this.verifyNum = 0;
      }
    },
    aliyunPlayerInfo(videoId) {
      aliVodInfo({
        videoId: videoId,
      }).then((res) => {
        if (res.code == 200) {
          this.$nextTick(()=>{
            this.Aliplayer.replayByVidAndPlayAuth(
              res.data.VideoMeta.VideoId,
              res.data.PlayAuth
            );
          })
        } else {
          this.$toast.fail("视频初始化错误");
        }
      });
    },

    //人脸验证 开始
    faceTimePause(time) {
      if (time == 0) {
        return;
      }
      this.facetimeObj = setTimeout(() => {
        this.CloseListening();
        // var isFull =
        //   document.webkitIsFullScreen ||
        //   document.mozFullScreen ||
        //   document.msFullscreenElement ||
        //   document.fullscreenElement;
        // if (isFull == null || isFull == undefined) {
        //   isFull = false;
        // }

        var setting = this.initObj?this.initObj.setting:''
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
          this.Aliplayer.pause();
          if(this.Aliplayer.fullscreenService.getIsFullScreen()){
            this.Aliplayer.fullscreenService.cancelFullScreen() || this.Aliplayer.exitFullscreen()
          }
        } else {
          this.$refs.videoPlayer.player.exitFullscreen();
          this.$refs.videoPlayer.player.pause();
        }
        this.disFace = true;
      }, time);
    },
    //视频练习 开始考试   getsubject_id()  getGZ()   getapplyid()
    async startVideoPractice() {
      var setting = false;
      await gzExamSetting({
        gz: getGZ(),
      }).then((res) => {
        if (res.code == 200) {
          if (JSON.stringify(res.data) == "{}") {
            setting = true;
            return this.$message.error("该工种无考试设置");
          } else {
            this.videoTestSetting = res.data;
          }
        }
      });

      if (setting) {
        return;
      }

      await videoPractice({
        subjectid: getsubject_id(),
        // gz: getGZ(),
        material_id: this.id,
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          // console.log(res, "777");
          if (res.data.list.length == 0) {
            this.$toast.fail("该视频暂无试题");
          } else {
            this.$store.commit("SET_TI", res.data.list);

            this.$router.push(
              "/videoPractice?video=" +
                true +
                "&quizid=" +
                res.data.quizid +
                "&gz=" +
                getGZ() +
                "&setting=" +
                JSON.stringify(this.videoTestSetting)
            );
          }
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    async videoData() {
      await materialList({
        msid: this.subjctid,
        file_type: "视频",
        page: 1,
        limit: 10000,
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          if (
            Object.keys(res.data).indexOf("scoreGqLimit") != -1 &&
            res.data.scoreGqLimit
          ) {
            this.overTime = 1;
            this.$dialog.confirm({
              title: "提示",
              message: "今天已学学时已达标，请明天继续学习",
              showCancelButton: false,
              confirmButtonText: "返回",
              closeOnClickOverlay: false,
              showClose: false,
              beforeClose: (action, done) => {
                if (action == "confirm") {
                  this.goBack();
                }
                done();
              },
            });
            return false;
          }
          res.data.list.map((item) => {
            let list = JSON.parse(item.material_subject_full);
            if (!item.cover_path) {
              for (let i = 0; i < learnImglist.length; i++) {
                for (let k = 0; k < list.length; k++) {
                  let el = list[k];
                  if (el && el.indexOf(learnImglist[i].id) != -1) {
                    item.cover_path = learnImglist[i].src;
                    break;
                  }
                }
              }
            }
          });
          this.dataList = res.data.list;
          if (!this.id) {
            var setting = this.initObj?this.initObj.setting:''
            if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
              this.aliyunPlayerInfo(this.dataList[0].MediaId);
            } else {
              this.playerOptions.sources[0].src = this.dataList[0].file_path;
            }
            this.titleName = this.dataList[0].title;
            this.id = this.dataList[0].id;
            if (this.dataList[0].done == 1) {
              this.isdone = true;
            }
          } else {
            this.dataList.map((item) => {
              if (item.id == this.id) {
                var setting = this.initObj?this.initObj.setting:''
                if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
                  this.aliyunPlayerInfo(item.MediaId);
                } else {
                  this.playerOptions.sources[0].src = item.file_path;
                }
                this.titleName = item.title;
                this.status = item.status;
                if (item.done == 1) {
                  this.isdone = true;
                }
              }
            });
          }
        }
      });
    },
    //pdflist
    async pdfList() {
      this.pdfOffIn = [];
      await materialList({
        msid: this.subjctid,
        file_type: "课件",
        page: 1,
        limit: 10000,
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          this.pdfOffIn = res.data.list;
        }
      });
    },
    //播放结束
    async onPlayerEnded(player) {
      this.isFalse = false;
      this.overTime = 1;
      await this.addLog(1);
      if (this.DialogVideoTest) {
        this.$dialog
          .confirm({
            title: "提示",
            message: "您已看完当前视频，是否前往练题?",
          })
          .then(() => {
            this.startVideoPractice();
          })
          .catch(() => {
            for (let index = 0; index < this.dataList.length; index++) {
              let item = this.dataList[index];
              if (item.id == this.id && this.dataList.length > index + 1) {
                this.studyClick(this.dataList[index + 1]);
                this.$refs.videoPlayer.player.play();
                break;
              }
            }
          });
        return;
      }
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index];
        if (item.id == this.id && this.dataList.length > index + 1) {
          this.studyClick(this.dataList[index + 1]);
          this.$refs.videoPlayer.player.play();
          break;
        }
      }
    },
    //阿里 播放结束
    PlayerEnded() {
      this.isFalse = false;
      this.overTime = 1;
      this.addLog(1);
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index];
        if (item.id == this.id && this.dataList.length > index + 1) {
          this.studyClick(this.dataList[index + 1]);
          this.Aliplayer.play();
          break;
        }
      }
    },
    // 当前播放位置发生变化时触发。
    onPlayerTimeupdate(player) {
      if (
        JSON.parse(this.initObj.setting) &&
        JSON.parse(this.initObj.setting).vadioSick != "开启"
      ) {
        //防止部分手机下拉任务栏拖动进度条
        if (Math.abs(player.currentTime() - this.nowTime) > 1) {
          player.currentTime(this.nowTime);
        } else {
          this.nowTime = player.currentTime();
        }
      }
      this.allplayertime = this.$refs.videoPlayer.player.duration();
      // console.log(this.allplayertime);
      // console.log(player.cache_.duration-player.cache_.currentTime)
      this.timeNow = Math.floor(player.cache_.currentTime);
      // this.overTime = 0
      // if(Math.floor(player.cache_.duration-player.cache_.currentTime==0)){
      //     console.log('12111')
      //     this.overTime = 1
      // }
    },

    //阿里 当前播放位置发生变化时触发。
    PlayerTimeupdate() {
      if (
        JSON.parse(this.initObj.setting) &&
        JSON.parse(this.initObj.setting).vadioSick != "开启"
      ) {
        //防止部分手机下拉任务栏拖动进度条
        if (Math.abs(this.Aliplayer.getCurrentTime() - this.nowTime) > 1) {
          this.Aliplayer.seek(this.nowTime);
        } else {
          this.nowTime = this.Aliplayer.getCurrentTime();
        }
      }
      this.allplayertime = this.Aliplayer.getDuration();
      // console.log(player.cache_.duration-player.cache_.currentTime)
      this.timeNow = Math.floor(this.Aliplayer.getCurrentTime());
    },
    //初始化视频进度
    async onPlayerLoadeddata(player) {
      // await this.jlLog(player);
      // alert(2)
      console.log(this.isFalse, "123333");
      // if (this.isFalse) {
      //   // alert(this.timeNowA)
      //   this.$refs.videoPlayer.player.currentTime(this.timeNowA);
      // } else {
      //   this.$refs.videoPlayer.player.currentTime(0);
      // }
      // this.$refs.videoPlayer.player.play();
      // let time = setTimeout(() => {

      //   clearTimeout(time)
      // }, 500);
    },
    //阿里 视频初始化完成
    PlayerLoadeddata() {
      if (this.isFalse) {
        // alert(this.timeNowA)
        this.Aliplayer.seek(this.timeNowA);
      } else {
        this.Aliplayer.seek(0);
      }
    },
    //将侦听器绑定到组件的就绪状态。与事件监听器的不同之处在于，如果ready事件已经发生，它将立即触发该函数。。 每次仅在初始化的时候执行一次
    async playerReadied(player) {
      // alert(1)
      this.isjllog = false;
      await this.jlLog(player);
      await this.$nextTick(() => {
        if (this.isFalse) {
          // alert(this.timeNowA)
          this.$refs.videoPlayer.player.currentTime(this.timeNowA);
        } else {
          this.$refs.videoPlayer.player.currentTime(0);
        }
        this.$refs.videoPlayer.player.play();
      });
    },
    async studyClick(item) {
      this.showVideo = true
      if (item.id == this.id) {
        //禁止连续点击
        return;
      }
      let subjctid = JSON.parse(JSON.stringify(this.$route.query.subjctid));
      let kj = JSON.parse(JSON.stringify(this.$route.query.kj));
      let MediaId = JSON.parse(JSON.stringify(this.$route.query.MediaId));
      this.$router.push({
        query: {
          id: item.id,
          subjctid: subjctid,
          kj: kj,
          // route: route,
          MediaId: MediaId,
          // "/video?id=" +
          //   item.id +
          //   "&subjctid=" +
          //   this.value +
          //   "&kj=" +
          //   this.pack +
          //   "&MediaId=" +
          //   item.MediaId
        },
      });

      this.status = item.status;
      if (item.done == 1) {
        this.isdone = true;
        this.isFalse = false;
      } else {
        this.isFalse = true;
        this.isdone = false;
      }
      if (this.overTime != 1) {
        await this.addLog(1);
      }
      this.overTime = 0;
      this.id = item.id;
      this.titleName = item.title;
      var setting = this.initObj?this.initObj.setting:''
      if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
        this.aliyunPlayerInfo(item.MediaId);
      } else {
        this.playerReadied();
        this.playerOptions.sources[0].src = item.file_path;
        this.$forceUpdate();
      }
      // this.cyclesNum=10
    },
    //后退
    goBack() {
      this.$router.push(
        `/study?kj=${this.$route.query.kj}&id=` + this.subjctid
      );
    },
    //保存
    async addLog(data) {
      this.isFalse = false;
      if (!this.timeNow) return;
      let duration = 100;
      let current = 0;
      var setting = this.initObj?this.initObj.setting:''
      if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
        duration = this.Aliplayer.getDuration();
        current = this.Aliplayer.getCurrentTime();
      } else {
        duration = this.$refs.videoPlayer.player.duration();
        current = this.$refs.videoPlayer.player.currentTime();
      }
      let mprogress = current / duration;
      mprogress = String(mprogress);
      mprogress = mprogress.substr(0, mprogress.indexOf(".") + 3);

      let obj = {
        mprogress: mprogress,
        mid: this.id,
        msid: this.subjctid,
        period: this.timeNow,
        done: this.overTime,
        applyid: getapplyid(),
        face: this.face,
      };

      await materialaddlog(obj).then((res) => {
        if (res.code == 210) {
          this.DialogVideoTest = true;
        }
        this.loading = false;
        if (!data) return false;
        this.timeNow = 0;
        this.videoData();
      });
      // await materialaddlog(obj).then((res) => {
      //   if (!data) return false;
      //   // this.timeNow=0

      //   // this.videoData()
      //   // for(let index=0;index<this.dataList.length;index++){
      //   //     let item =this.dataList[index]
      //   //     if(item.id==this.id&&this.dataList.length>index+1){
      //   //         this.studyClick(this.dataList[index+1])
      //   //         this.$refs.videoPlayer.player.play()
      //   //         break
      //   //     }
      //   // }
      // });
    },
    //获取学习记录
    async jlLog(player) {
      this.isjllog = true;
      await materiallearnlog({
        applyid: getapplyid(),
        mid: this.id,
        limit: 80,
      }).then((res) => {
        if (res.code == 200) {
          let isfor = false;
          res.data.list.map((item) => {
            if (item.done) {
              isfor = true;
            }
          });
          // console.log(isfor,res.data.list[0].period);
          if (isfor) {
            this.isFalse = false;
            this.timeNowA = 0;
          } else {
            this.isFalse = true;
            this.timeNowA = res.data.list[0] ? res.data.list[0].period : 0;
            this.nowTime = res.data.list[0] ? res.data.list[0].period : 0;
          }
          // player.on('loadedmetadata',()=>{
          //   this.$refs.videoPlayer.player.currentTime(this.timeNowA);
          // })
          // this.$refs.videoPlayer.player.play()
        }
      });
    },
    async play() {
      // if(!this.isjllog){
      //   await this.jlLog();
      // }
    },
    clickXq(row) {
      console.log(row);
      quizRedo({ quizid: row.id }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.$store.commit("SET_TI", res.data.list);
          this.$router.push(
            "/classExam?quizid=" + res.data.quizid + "&gz=fj"
          );
        }
      });
    },
    //随堂练习 开始考试   getsubject_id()  getGZ()   getapplyid()
    startExam() {
      quizStart({
        subjectid: getsubject_id(),
        gz: getGZ(),
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          this.$store.commit("SET_TI", res.data.list);
          this.$router.push(
            "/classExam?quizid=" + res.data.quizid + "&gz=" + getGZ()
          );
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    classFunction() {
      let u = navigator.userAgent;
      let isIOS = u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (this.isquerymodel) {
        // iphonebox  iphonebox
        return "video-player vjs-custom-skin";
      } else {
        if (isIOS) {
          return "video-player vjs-custom-skin isShowModel";
        } else {
          return "video-player vjs-custom-skin isShowModel";
        }
      }
    },
    async getInfo() {
      await getSetting({ subjectid: this.subjctid, gz: getGZ() }).then(
        (res) => {
          let obj = {};
          if (res.code == 200) {
            let arr = ["初级", "中级", "高级", "技师"];
            if (
              getGZ() == "职业技能等级认定" &&
              (this.http.indexOf("qdjsxy") != -1 ||
                this.http.indexOf("qiye") != -1 ||
                this.http.indexOf("testtjy") != -1)
            ) {
              arr.map((item) => {
                if (getsubjectTitle().indexOf(item) != -1) {
                  obj = res.data.随堂练习[item];
                }
              });
            } else {
              obj = res.data.随堂练习;
            }

            setExectSetting(Object.assign(obj, { 考试类型: "随堂练习" }));
          }
        }
      );
    },
    //查看下一个知识点
    serachKnow() {
      materialkmlist({
        msid: getsubject_id(),
        applyid: getapplyid(),
        cate: "理论",
      }).then((res) => {
        if (res.code == 200) {
          for (let index = 0; index < res.data.length; index++) {
            const item = res.data[index];
            if (item.id == this.subjctid) {
              console.log(item.id, this.subjctid);
              if (index + 1 >= res.data.length) {
                this.$toast.fail("已是最后一个知识点!!!");
                break;
              } else {
                this.subjctid = res.data[index + 1].id;
                this.id = null;
                this.videoData();
                break;
              }
            }
          }
        }
      });
    },

    //跳转PDF课件
    goPDFList() {
      this.$router.push(`/study?kj=课件&id=${this.subjctid}`);
    },
  },
  created() {
    this.getInfo();
    var setting = this.initObj?this.initObj.setting:''
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器'){
      this.aliDom = true
    }else{
      this.aliDom = false
    }
    if (
      this.initObj.is_face &&this.Jurisdictions.gz&&
      JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface !=
        "关闭" &&
      JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime
    ) {
      this.facetime = 0;
      if (
        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime ==
        "随机"
      ) {
        this.facetime =
          Math.floor(
            Math.random() *
              (Number(
                JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                  .kjfacetimeEnd
              ) -
                Number(
                  JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                    .kjfacetimeStart
                ) +
                1)
          ) +
          Number(
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetimeStart
          );
      } else if (
        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime ==
        "省厅规则"
      ) {
        this.facetime = 0;
      } else {
        this.facetime = JSON.parse(this.initObj.is_face)[
          this.Jurisdictions.gz
        ].kjfacetime;
      }
      this.faceTimePause(this.facetime * 60 * 1000);
      // time * 60 * 1000
    }

    this.isquerymodel =
      JSON.parse(this.initObj.setting) &&
      JSON.parse(this.initObj.setting).vadioSick
        ? !(JSON.parse(this.initObj.setting).vadioSick == "关闭")
        : true;
    if (JSON.parse(getcurrentInfo()).drag_video_progress) {
      this.isquerymodel =
        JSON.parse(getcurrentInfo()).drag_video_progress == "开启";
    }
    if (!this.isquerymodel) {
      if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
        this.controlBarChildren = this.controlBarChildren.filter(
          (item) => item.name != "progress"
        ); //禁用进度条快进
      } else {
        this.playerOptions.playbackRates = [1.0];
      }
    }
    if(!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
      this.controlBarChildren = this.controlBarChildren.filter(
          (item) => (item.name != "fullScreenButton"&&item.name != "volume")
      ); //ios禁用全屏及音量键
    }
    this.showVideo = this.$route.query.showVideo ? false : true;
    this.overTime = 0;

    this.loadingA = true;
    quizMylist({ applyid: getapplyid() }).then((res) => {
      this.loadingA = false;
      if (res.code == 200) {
        this.tableData = res.data.list;
      }
    });
    // window.addEventListener('unload',this.onunload)
  },
  async mounted() {
    // console.log(this.$refs.videoPlayer.player,'4');
    var setting = this.initObj?this.initObj.setting:''
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
      var that = this;
      Aliplayer.__unable2Anti9Debugger13Key = "error";
      await aliVodInfo({
        videoId:
          this.$route.query.MediaId || "b3e53bb0012071eeb07c6eb3690d0302",
      }).then((res) => {
        if (res.code == 200) {
          new Aliplayer(
            {
              controlBarVisibility: "click",
              showBarTime: "5000",
              id: "J_prismPlayer",
              vid: res.data.VideoMeta.VideoId,
              diagnosisButtonVisible: false, // 诊断按钮
              // encryptType: 1, //当播放私有加密流时需要设置本参数值为1。其它情况无需设置。
              playConfig: {
                // EncryptType: "AliyunVoDEncryption",
                PlayDomain: "video.taijieyun.com",
              },
              defaultDefinition:'LD',
              definition:that.initObj.hd_video.includes(getGZ())?'FD,LD,SD':'FD,LD',
              playauth: res.data.PlayAuth, //视频的播放凭证，可以在通用媒体管理服务控制台获取。
              skinLayout: [
                { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
                {
                  name: "H5Loading",
                  align: "cc",
                },
                { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
                { name: "infoDisplay" },
                { name: "tooltip", align: "blabs", x: 0, y: 56 },
                { name: "thumbnail" },
                {
                  name: "controlBar",
                  align: "blabs",
                  x: 0,
                  y: 0,
                  children: that.controlBarChildren,
                },
              ],
              components: this.isquerymodel
                ? [
                    {
                      name: "QualityComponent",
                      type: AliPlayerComponent.QualityComponent,
                      // args: [function(definition,desc) {
                      //   console.log(definition + '-----' + desc)
                      // }]
                    },
                    {
                      name: "RateComponent",
                      type: AliPlayerComponent.RateComponent,
                    },
                  ]
                : [
                    {
                      name: "QualityComponent",
                      type: AliPlayerComponent.QualityComponent,
                      // args: [function(definition,desc) {
                      //   console.log(definition + '-----' + desc)
                      // }]
                    },
                  ],
            },
           async function (player) {
              await that.jlLog();
              // console.log(AliPlayerComponent);
              that.Aliplayer = player;
              that.Aliplayer.on("ready", that.PlayerLoadeddata);
              player
                .getComponent("QualityComponent")
                .setCurrentQuality('标清', 'LD');
              that.Aliplayer.on("canplay", () => {
                that.loading = false;
              });
              that.Aliplayer.on("timeupdate", that.PlayerTimeupdate);
              that.Aliplayer.on("ended", that.PlayerEnded);
              that.Aliplayer.play();
            }
          );
        } else {
          this.$toast.fail("视频初始化错误");
        }
      });
    }
    let NotOperated = JSON.parse(this.initObj.setting).NotOperated;
    this.windowTime = NotOperated * 60;
    // NotOperated
    if (this.windowTime && this.windowTime != 0) {
      this.OpenListening();
      this.notAlpay(this.windowTime);
    }
    this.videoData();
    // console.log(3333);
    this.pdfList();
    // this.OpenListening()
    // this.notAlpay(this.windowTime)
    
  },
  beforeDestroy() {
    this.CloseListening();
    clearTimeout(this.windowPcltime);
    var setting = this.initObj?this.initObj.setting:''
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
      this.Aliplayer.off("ended", this.PlayerEnded);
      this.Aliplayer.off("canplay", this.PlayerLoadeddata);
      this.Aliplayer.off("timeupdate", this.PlayerTimeupdate);
      this.Aliplayer.dispose();
    }
    if (this.showVideo && !this.overTime) {
      this.addLog();
    }
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .videoPractice {
    background: #327bff;
    border-color: #327bff;
    width: 100%;
    margin-top: 1rem;
    height: 2.6rem !important;
    font-size: 14px !important;
  }
}
.video_title {
  display: flex;
  align-items: center;
  padding: 0 12px;
  background: #327bff;
  color: #fff;
  height: 2.75rem;

  p {
    margin: 0;
    width: calc(100vw - 64px);
    display: flex;
    justify-content: center;
  }

  .icon {
    font-size: 1.25rem;
  }
}

.videoName {
  font-size: 1.125rem;
  font-weight: 600;
  padding: 0.8rem;
  background: #fff;
  p {
    margin: 0;
  }
}

.aivterLi {
  p {
    color: #175dff;
  }
}

.video_content {
  margin-top: 0.625rem;
  padding: 0 0.75rem;
  // height: calc(100vh - 2.75rem );
  flex: 1;
  overflow: auto;

  li {
    background: #fff;
    padding: 0.75rem;
    border-top: 1px solid #eee;
    list-style: none;
    display: flex;
    justify-content: space-between;
    height: 5.8rem;
    margin-bottom: 0.75rem;
    .font-box {
      display: flex;
      width: 100%;
      i {
        line-height: 35px;
      }
      & > div {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        img {
          width: 100%;
        }
      }
      p {
        font-size: 0.98rem;
        margin: 0;
        font-weight: 600;
        display: flex;
        align-items: center;
        max-width: 15rem;
        overflow: hidden;
        text-overflow: -o-ellipsis-lastline;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2; //超出两行省略
        line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      span {
        font-size: 0.75rem;
        color: #999;
      }
    }
    .img_box {
      height: 100%;
      display: flex;
      align-items: center;
      img {
        height: 100%;
      }
      .img_text {
        width: 4.375rem;
        height: 1.56rem;
        background: #327bff;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 0.875rem;
        border-top-left-radius: 0.75rem;
        border-bottom-right-radius: 0.75rem;
      }
    }
    &:first-child {
      border: none;
    }
  }
}

::v-deep {
  .varify-input-code {
    background: #eee !important;
  }
  // .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover, .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active, .video-js .vjs-volume-panel.vjs-volume-panel-horizontal:active{
  //     width: auto;
  // }
  // .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover, .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active, .video-js .vjs-volume-panel.vjs-volume-panel-horizontal{
  //     width:7em;
  // }
  // .video-js .vjs-volume-panel.vjs-hover .vjs-volume-control, .video-js .vjs-volume-panel:active .vjs-volume-control, .video-js .vjs-volume-panel:focus .vjs-volume-control, .video-js .vjs-volume-panel .vjs-volume-control:active, .video-js .vjs-volume-panel.vjs-hover .vjs-mute-control ~ .vjs-volume-control, .video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active{
  //     // opacity: 1;
  //     position:absolute;
  //     transform:rotate(-90deg);
  //     top: -3.6em;
  //     left:-1em;
  // }
}

.stBox {
  height: 211px;
  overflow: auto;
  width: 100%;
  padding: 0.75rem;

  // background: chartreuse;
  .li {
    background: #fff;
    padding: 0.75rem;
    height: 5.5rem;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-top: 0.75rem;
    border-radius: 5px;

    &:first-child {
      margin-top: 0;
    }

    p {
      margin: 0;
    }

    div {
      display: flex;
    }

    .li-top {
      p {
        width: 50%;
      }

      span {
        font-size: 1.2rem;
        font-weight: 600;
      }

      i {
        font-size: 1.2rem;
        color: #175dff;
      }
    }

    .li-bottom {
      p {
        // width: 50%;
        &:first-child {
          width: 40%;
        }
      }

      span {
        font-size: 0.8rem;
      }

      i {
        font-size: 0.8rem;
        color: rgba($color: #000000, $alpha: 0.5);
      }
    }
  }
}

.card {
  display: none;
  width: 6.25rem;
  height: 1rem;
  background: #f00;
  position: absolute;
  transform: rotate(40deg);
  top: 10px;
  right: -35px;
}

.cardText {
  display: none;
  position: absolute;
  // padding:10px;
  font-size: 0.75rem;
  transform: rotate(40deg);
  top: 7px;
  right: -1px;
  color: #fff;
  z-index: 2;
}

.content_text_boxA {
  position: relative;
  overflow: hidden;
  width: 6.25rem;
  margin-right: 1rem;

  .card {
    display: block;
  }

  .cardText {
    display: block;
  }
}

.isShowModel {
  ::v-deep {
    .vjs-progress-control {
      display: none !important;
    }
  }
}

.iphonebox {
  ::v-deep {
    .vjs-fullscreen-control {
      display: none !important;
    }
  }
}
</style>
